#include "../../../../mac/mem.h"

#define BOOK_NUM 10

typedef struct book {
    struct book *next;
    int id;
} book_t;

MEM(b_free_list);
book_t b_mem[BOOK_NUM];
LIST(b_list);

char b_init()
{
    pool_t p;

    p.ptr = b_mem;
    p.num = BOOK_NUM;
    p.size = sizeof(book_t);

    memset(b_mem, 0, sizeof(b_mem));
    list_init(b_list);
    return mem_init(b_free_list, &p);
}

/* return the id of the allocated book */
int b_alloc(int id)
{
    book_t *b;

    b = mem_alloc(b_free_list);
    if (b == NULL)
        return MEM_ERR;

    b->id = id;
    list_add_head(b_list, b);

    b = list_get_head(b_list);
    if (b != NULL)
        return b->id;
    else 
        return MEM_ERR;
}

char b_free(int id)
{
    book_t *b = list_get_head(b_list);

    for (; b != NULL; b = b->next) {
        if (b->id == id) {
            break;
        }
    }

    if (b == NULL) {
        return MEM_NO_ITEM;
    } else {
        list_del(b_list, b);
        return mem_free(b_free_list, b);
    }
}



